package com.ddw.weewar.api;

import android.os.AsyncTask;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * Represents a weewar user request
 */
class WeewarUserRequest extends AsyncTask<Void, Void, WeewarUser> {

    private static final String sAttId = "id";
    private static final String sAttUsername = "name";
    private static final String sNodePoints = "points";
    private static final String sNodeProfile = "profile";
    private static final String sNodeReadyToPlay = "readyToPlay";
    private static final String sNodeGamesRunning = "gamesRunning";
    private static final String sNodeGames = "games";
    private static final String sNodeGame = "game";
    private static final String sAttGameName = "name";

    private Throwable mError = null;
    private final String mUsername;
    private final WeewarApi.UserCallback mCallback;

    /**
     * Creates a new weewar user request instance
     * @param username the username of the user to find
     * @param callback the callback to respond to
     */
    WeewarUserRequest(String username, WeewarApi.UserCallback callback) {
        this.mUsername = username;
        this.mCallback = callback;
    }

    @Override
    protected WeewarUser doInBackground(Void... voids) {
        try {
            // Create the url
            String url = "http://weewar.com/api1/user/" + this.mUsername;

            // Get the response
            String response = HttpUtils.get(url);

            // Parse as xml
            Element document = XmlUtils.parse(response).getDocumentElement();

            // Parse the xml into our user
            WeewarUser user = new WeewarUser();

            /* Example xml structure for weewar user

            <user name="fungus1487" id="130505">
                <points>1500</points>
                <profile>http://weewar.com/user/fungus1487</profile>
                <profileImage>http://weewar.com/images/no_profile_small.gif</profileImage>
                <draws>0</draws>
                <victories>0</victories>
                <losses>0</losses>
                <accountType>Pro</accountType>
                <on>true</on>
                <readyToPlay>false</readyToPlay>
                <gamesRunning>2</gamesRunning>
                <lastLogin>2013-08-14 14:43:06.0</lastLogin>
                <basesCaptured>18</basesCaptured>
                <creditsSpent>14275</creditsSpent>
                <favoriteUnits>
                    <unit code="lightInfantry"/>
                    <unit code="heavyInfantry"/>
                    <unit code="lighttank"/>
                    <unit code="hovercraft"/>
                    <unit code="tank"/>
                    <unit code="lightartillery"/>
                    <unit code="speedboat"/>
                    <unit code="sub"/>
                    <unit code="fighter"/>
                    <unit code="destroyer"/>
                    <unit code="antiair"/>
                </favoriteUnits>
                <preferredPlayers/>
                <games>
                    <game name="A lonely war.">433968</game>
                    <game name="one on one">434130</game>
                </games>
                <maps/>
            </user>
             */

            // Get the user values
            user.setId(Long.parseLong(document.getAttributeNode(sAttId).getTextContent()));
            user.setUsername(document.getAttributeNode(sAttUsername).getTextContent());
            user.setPoints(Long.parseLong(document.getElementsByTagName(sNodePoints).item(0).getTextContent()));
            user.setProfile(document.getElementsByTagName(sNodeProfile).item(0).getTextContent());
            user.setReadyToPlay(Boolean.parseBoolean(document.getElementsByTagName(sNodeReadyToPlay).item(0).getTextContent()));
            user.setGamesRunning(Long.parseLong(document.getElementsByTagName(sNodeGamesRunning).item(0).getTextContent()));

            // Add each game
            NodeList games = ((Element) document.getElementsByTagName(sNodeGames).item(0)).getElementsByTagName(sNodeGame);
            Element game;
            for(int i = 0, s = games.getLength(); i < s; i++) {
                game = (Element) games.item(i);
                user.getGames().put(
                        Long.parseLong(game.getTextContent()),
                        game.getAttributeNode(sAttGameName).getTextContent());
            }

            return user;
        } catch (Throwable e) {
            this.mError = e;
            return null;
        }
    }

    @Override
    protected void onPostExecute(WeewarUser user) {
        super.onPostExecute(user);

        if(this.mError != null) {
            this.mCallback.onFailure(this.mError);
        } else {
            this.mCallback.onSuccess(user);
        }
    }

}
